#include "Projectile.h"
#include "Game.h"

Projectile::Projectile(Entity* owner, Image* image, int x, int y, float u, float v, byte damage, bool hitPlayerOnly, bool gravity) : Entity()
{
	this->x = x;
	this->y = y;
	this->u = u;
	this->v = v;

	this->owner = owner;
	this->image = image;
	this->damage = damage;
	this->hitPlayerOnly = hitPlayerOnly;

	applyGravity = gravity;

	flipped = (u > 1.0f) ? false : true;

	health = 5;

	alive = true;
}

Projectile::~Projectile()
{
	// Projectile image managed elsewhere
}

void Projectile::tick()
{
	if(alive)
	{
		if(hitPlayerOnly)
		{
			checkEntity( Game::getInstance()->getPlayer() );
		}
		else
		{
			list<Entity*>* entities = Game::getInstance()->getEntities();
			for(list<Entity*>::iterator i = entities->begin(); i != entities->end(); i++)
			{
				if( checkEntity(*i) ) break;
			}
		}

		if( y <= 0.0f){
			alive = false;
		}
		if( !withinRange() )
		{
			expired = true;
		}
	}
	else
	{
		printf("deaded\n");
	}
}

bool Projectile::checkEntity(Entity* e)
{
	if(e != this && e != owner && e->isAlive() && e->collidesWith(this))
	{
		e->damage(damage, this);
 		expired = true;
		return true;
	}

	return false;
}
